package com.mgg.common.dao;

import com.mgg.common.exception.DAOException;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository("daoSupport")
public class DaoSupport implements DAO {

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	
	/**
	 * 保存对象
	 * @param statement
	 * @param obj
	 * @return
	 */
	public Integer save(String statement, Object obj){
		Integer count = null;
		try {
			count = sqlSessionTemplate.insert(statement, obj);
		} catch (Exception e) {
            throw new DAOException(e.getMessage(),e);
		}
		return count;
	}
	
	/**
	 * 修改对象
	 * @param statement
	 * @param obj
	 * @return
	 */
	public Integer update(String statement, Object obj){
        Integer count = null;
        try {
            count = sqlSessionTemplate.update(statement, obj);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(),e);
        }
        return count;
	}
	
	/**
	 * 删除对象 
	 * @param statement
	 * @param obj
	 * @return
	 */
	public Integer delete(String statement, Object obj){
        Integer count = null;
        try {
            count = sqlSessionTemplate.delete(statement, obj);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(),e);
        }
        return count;
	}
	 
	/**
	 * 查找对象
	 * @param statement
	 * @param obj
	 * @return
	 */
	public <T> T findForObject(String statement, Object obj){
        T t;
        try {
            t = sqlSessionTemplate.selectOne(statement, obj);
        } catch (Exception e) {
            System.out.println("Exception");
            throw new DAOException(e.getMessage(),e);
        }
        return t;
	}

	/**
	 * 查找对象
	 * @param statement
	 * @param obj
	 * @return
	 */
	public <E> List<E> findForList(String statement, Object obj){
        List<E> list;
        try {
            list = sqlSessionTemplate.selectList(statement, obj);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(),e);
        }
        return list;
	}
	
	public <K, V> Map<K, V> findForMap(String statement, Object parameter, String mapKey){
        Map<K, V> map;
        try {
            map = sqlSessionTemplate.selectMap(statement, parameter, mapKey);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(),e);
        }
        return map;
	}
}


